<?php
namespace app\api\controller\vppz;


use think\Cache;

use \app\admin\model\vppz\PhysicalExamPackage as PhysicalExamPackageModel;
use \app\admin\model\vppz\PhysicalPackageItemRel as PhysicalPackageItemRelModel;
use \app\admin\model\vppz\PhysicalExam as PhysicalExamModel;
use \app\admin\model\vppz\Hospital as HospitalModel;
use \app\admin\model\vppz\ExaminationCategory as PhysicalExamCategoryModel;
use \app\admin\model\vppz\ExaminationOrder as ExaminationOrderModel;
use \app\admin\model\vppz\ExaminationOrderDetail as ExaminationOrderDetailModel;
use \addons\vppz\library\Vpower;
use function fast\e;

class Physical extends App
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();
        $this->model = new PhysicalExamPackageModel;
        $this->PhysicalPackageItemRelModel = new PhysicalPackageItemRelModel;
        $this->PhysicalExamModel = new PhysicalExamModel;
        $this->HospitalModel = new HospitalModel;
        $this->PhysicalExamCategoryModel = new PhysicalExamCategoryModel;
        $this->ExaminationOrderModel = new ExaminationOrderModel;
        $this->ExaminationOrderDetailModel = new ExaminationOrderDetailModel;
        $config = \think\App::initCommon();
    }
    /**
     * 套餐列表
     * @return void
     */
    public function packagelists(){
        /**
         * id: 1,
		        name: "中老年基础体检套餐",
		        hospital_name: "北京健康医院",
		        hospital_level: "三级甲等",
		        people_type: "45岁以上中老年",
		        total_original_price: 365.00,
		        total_discount: 65.00,
		        final_price: 300.00,
		        required_count: 2,
		        optional_count: 3
         */
        $area=$this->_area;
		$keyword = input('keyword','');
		$hospital = input('hospital','');
		$peopleType = input('peopleType','');
		$pageSize = input('pageSize','10');
		$page = input('page','1');

		// 获取套餐
		$packageModel = $this->model->where([
            'app_id'=>$this->app_id,
            'is_active'=>1]);
        if(empty($hospital) === FALSE){
            $packageModel = $packageModel->whereLike('hospital_name',"%".$hospital."%");
        }
        if(empty($peopleType) === FALSE){
            $packageModel = $packageModel->whereLike('people_type',"%".$peopleType."%");
        }
        if(empty($keyword) === FALSE){
            $packageModel = $packageModel->whereLike('people_type|hospital_name|name',"%".$keyword."%");
        }
        $package = $packageModel->limit(($page-1)*$pageSize,$pageSize)->order('updatetime','desc')->select();

        $packagecountModel = $this->model->where([
            'app_id'=>$this->app_id,
            'is_active'=>1]);
        if(empty($hospital) === FALSE){
            $packagecountModel = $packagecountModel->whereLike('hospital_name',"%".$hospital."%");
        }
        if(empty($peopleType) === FALSE){
            $packagecountModel = $packagecountModel->whereLike('people_type',"%".$peopleType."%");
        }
        if(empty($keyword) === FALSE){
            $packagecountModel = $packagecountModel->whereLike('people_type|hospital_name|name',"%".$keyword."%");
        }
        $total = $packagecountModel->count();
        if(empty($package) === FALSE){
            foreach ($package as $k=>$v){
                $package[$k]['hospital_level'] = $config['hospital_level'][$v['hospital_level']]??'三级';

                $required_count = 0;
                $optional_count = 0;
                $required_count = $this->PhysicalPackageItemRelModel->where([
                    'package_id'=>$v['id'],
                    'item_type'=>1
                ])->count();
                $optional_count = $this->PhysicalPackageItemRelModel->where([
                    'package_id'=>$v['id']
                ])->whereIn('item_type','1,2')->count();
                $package[$k]['required_count'] = $required_count;
                $package[$k]['optional_count'] = $optional_count;
                if($v['cate_id'] == 'multi'){
                    //单项总折扣
                    $getprice = $this->PhysicalPackageItemRelModel->where([
                        'package_id'=>$v['id'],
                        'item_type'=>2
                    ])->select();
                    $all_price = 0;
                    $discount = 0;
                    if(empty($getprice) === FALSE){
                        $itemids = [];
                        foreach ($getprice as &$vv){
                            $discount+=$vv['item_discount'];
                            array_push($itemids,$vv['item_id']);
                        }
                        $all_price = $this->PhysicalExamModel->whereIn('id',$itemids)->sum('price');
                    }
                    $package[$k]['total_original_price'] = sprintf("%.2f",$all_price+$v['total_original_price']);
                    $package[$k]['final_price'] = sprintf("%.2f",$all_price-$discount+$v['final_price']);
                    $package[$k]['total_discount'] = sprintf("%.2f",$discount+($v['total_original_price']-$v['final_price']));
                }else if ($v['cate_id'] == 'auto'){
                    $package[$k]['total_original_price'] = 0;
                    $package[$k]['final_price'] = 0;
                    //单项总折扣
                    $getprice = $this->PhysicalPackageItemRelModel->where([
                        'package_id'=>$v['id'],
                        'item_type'=>2
                    ])->select();
                    $all_price = 0;
                    $discount = 0;
                    if(empty($getprice) === FALSE){
                        $itemids = [];
                        foreach ($getprice as &$vv){
                            $discount+=$vv['item_discount'];
                            array_push($itemids,$vv['item_id']);
                        }
                        $all_price = $this->PhysicalExamModel->whereIn('id',$itemids)->sum('price');
                    }
                    $package[$k]['total_original_price'] = $all_price;
                    $package[$k]['final_price'] = sprintf("%.2f",$all_price-$discount);
                    $package[$k]['total_discount'] = $discount;
                }
            }
        }
		$this->success('',array(
			'now'=>time(),
			'list'=>$package,
            'total'=>$total
		));
    }

    /**
     * 获取检索条件
     * @return void
     */
    public function getsearchdata(){
        $hospital = ['全部医院', '北京健康医院', '上海体检中心', '广州康复医院'];
        $peopletype = ['适用人群', '普通人群', '中老年人群', '青少年', '孕妇', '职场人士'];
        $packageModel = $this->model->where([
            'app_id'=>$this->app_id,
            'is_active'=>1]);
        $hospital = $packageModel->group('hospital_name')->column('hospital_name');

        $packagetypeModel = $this->model->where([
            'app_id'=>$this->app_id,
            'is_active'=>1]);
        $peopletype = $packagetypeModel->group('people_type')->column('people_type');
        $this->success('',array(
			'now'=>time(),
			'hospital'=>$hospital,
            'peopletype'=>$peopletype
		));
    }

    /**
     * 详情
     * @return void
     */
    public function detail(){

		$id = input('id');
        /**
         *  id: 1,
	            name: "中老年基础体检套餐",
	            hospital_name: "北京健康医院",
	            hospital_level: "三级甲等",
	            hospital_address: "北京市海淀区健康路88号",
	            hospital_phone: "010-88776655",
	            hospital_business_hours: "周一至周日 07:30-18:00",
	            people_type: "45岁以上中老年",
	            description: "包
         */
		$package = $this->model->find($id);
		if(empty($package)){
			$this->error('不存在或暂停提供');
		}
        $package->hospital_address = "未指定体检医院";
        if(empty($package['hospital_id']) === FALSE) {
            $hospital = $this->HospitalModel->find($package['hospital_id']);
            if (empty($hospital) === FALSE) {
                $package->hospital_address = $hospital->address;
            }
        }
        $package->hospital_level = $config['hospital_level'][$package->hospital_level]??'三级';
        $itemdata = [];

        $itemDatas = $this->PhysicalPackageItemRelModel->where(array(
            'package_id'=>$id
        ))->select();
        if(empty($itemDatas) === FALSE) {
            foreach ($itemDatas as $row) {
                /**
                 * id: 1,
	              name: "身高体重",
	              price: 15.00,
	              description: "测量身高、体重及BMI指数",
	              item_type: 1, // 必选
	              item_discount: 0.00,
	              checked: true
                 */
                $item = $this->PhysicalExamModel->find($row['item_id']);
                $check = false;
                if($row['item_type'] == 1 || $row['item_type'] == 2){
                    $check = true;
                }
                $category = $this->PhysicalExamCategoryModel->find($item->category_id);
                $data = array(
                    'id'=>$item->id,
                    'name'=>$item->name,
                    'price'=>$item->price,
                    'category_id'=>$item->category_id,
                    'category_name'=>empty($category) ? '常规体检' : $category->name,
                    'description'=>$item->description,
                    'item_type'=>$row['item_type'],
                    'item_discount'=>$row['item_discount'],
                    'discount'=>sprintf("%.2f",$item->price-$row['item_discount']),
                    'checked'=>$check,
                );
                array_push($itemdata,$data);
            }
        }
		$this->success('',array(
			'now'=>time(),
			'package'=>$package,
            'itemdata'=>$itemdata
		));
    }

    /**
     * 体检订单列表
     * @return void
     */
    public function orderlist(){
        $cfg=$this->_cfg;
		$area=$this->_area;
		$mine=$this->_mine;

		// 我的订单
		$start=input('start');
		if(!isset($start) || empty($start) || intval($start<=0)){
			$start=0;
		}else{
			$start=intval($start);
		}
		$limit=200;

		$where=[
			'app_id'=>$this->app_id,
			'user_id'=>$mine['id']
		];
		// 全部，待支付，进行中，已完成，已取消
		$filt = input('filt');
		if(!empty($filt) && $filt > 0){
			$filt=intval($filt);
			$where['status']=$filt;
            $list = $this->ExaminationOrderModel->where($where)->limit($start,$limit)->order('updatetime','DESC')->select();
		}else{
            $list = $this->ExaminationOrderModel->where($where)->whereIn('status',[1,3,4])->limit($start,$limit)->order('updatetime','DESC')->select();
        }
        $reslists = [];
		foreach ($list as $index=>$item){

            $detail = $this->ExaminationOrderDetailModel->where([
                'order_id'=>$item['id']
            ])->select();
            if (empty($detail) === FALSE){
                $item['report_status'] = $item['status'];
                foreach ($detail as &$dv){
                    if (empty($dv['report_url']) === FALSE){
                        $item['report_status'] = 5;
                    }
                }
            }
            switch ($item['status']){
                case 1:
                    $statusText = '待核销';
                    break;
                case 2:
                    $statusText = '已取消';
                    break;
                case 3:
                    $statusText = "待查看报告";
                    break;
                case 4:
                    $statusText = '已完成';
                    break;
            }
            if($item['status'] != 4 && $item['report_status'] == 5){
                $statusText = '部分完成';
            }
            $res = array(
                'orderId'=>$item['id'],
                'orderNo'=>$item['order_no'],
                'status'=>$item['status'],
                'statusText'=>$statusText,
                'hospitalName'=>$item['hospital_name'],
                'packageName'=>$item['package_name'],
                'examDate'=>$item['exam_date'],
                'personName'=>$item['exam_person_name'],
                'personPhone'=>$item['exam_person_phone'],
                'verifyCode'=>$item['order_no'],
                'hospital_level'=>$item['hospital_level'],
                'hospital_address'=>$item['hospital_address'],
                'report_status'=>$item['report_status']
            );
            $detailData = [];
            if(empty($detail) === FALSE){
                foreach ($detail as &$v){
                    $package_item = $this->PhysicalPackageItemRelModel->where([
                        'item_id'=>$v['item_id'],
                        'package_id'=>$item['package_id']
                    ])->find();
                    if(empty($package_item)){
                        $package_item_type = 1;
                    }else{
                        $package_item_type = $package_item->item_type;
                    }
                    $resd = array(
                        'id'=>$v['item_id'],
                        'name'=>$v['item_name'],
                        'price'=>$v['item_price'],
                        'item_type'=>$package_item_type,
                        'description'=>$v['item_description'],
                        'hospital_name'=>$v['hospital_name'],
                        'hospital_level'=>$v['hospital_level'],
                        'hospital_address'=>$v['hospital_address']
                    );
                    array_push($detailData,$resd);
                }
            }
            $res['isExpanded'] = false;
            $res['projects'] = $detailData;
            array_push($reslists,$res);
		}
		$more=1;
		if(empty($reslists) || count($reslists)<$limit){
			$more=0;
		}
		$start+=count($reslists);

		$this->success('',array(
			'now'=>time(),
			'list'=>$reslists,
			'start'=>$start,
			'more'=>$more
		));
    }
    //核销记录
    public function hexiaohistory(){
        $hospitalid = input('hospitalId','');
        if(empty($hospitalid)){
            $this->error('参数有误');
            return false;
        }
        $pageNum = input('pageNum',1);
        $pageSize = input('pageSize',10);
        $notes = $this->ExaminationOrderModel
            ->where(['hexiao_hospital_id'=>$hospitalid])->whereIn('status',[3,4])
            ->order('exam_complete_time','DESC')->limit(($pageNum-1)*$pageSize,$pageSize)
            ->select();
        $total = $this->ExaminationOrderModel
            ->where(['hexiao_hospital_id'=>$hospitalid])->whereIn('status',[3,4])->count();
        $res = [];
        if(empty($notes) === FALSE){
            foreach ($notes as $bk=>$bj){
                $bj['createtime'] = date('Y-m-d H:i:s',$bj['createtime']);
                $bj['updatetime'] = date('Y-m-d H:i:s',$bj['updatetime']);
                $bj['exam_complete_time'] = date('Y-m-d H:i:s',$bj['exam_complete_time']);

                //获取优惠券信息
                $bj['name'] = $detail['package_name']??'体检套餐';
                $bj['hospitalName'] = $bj['hexiao_hospital_name'];
                $res[] = $bj;
            }
        }
		$this->success('',array(
			'total'=>$total,
			'lists'=>$res
		));
    }
    public function checkPhysicalCode(){
        $couponCode = input('code','');
        $hospitalid = input('hospitalId','');
        if(empty($hospitalid) || empty($couponCode)){
            $this->error('参数有误');
            return false;
        }
        $order = $this->ExaminationOrderModel->where(['order_no'=>$couponCode])
            ->field('hospital_id,status')->find();
        if(empty($order)){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'体检码有误，请核实后使用'
            ));
        }else if(empty($order->hospital_id) === FALSE){
            if($order->hospital_id != $hospitalid){
                $this->success('成功',array(
                    'code'=>400,
                    'data'=>[],
                    'msg'=>'体检码不属于当前医院，请核实后使用'
                ));
            }
        }
        if($order->status == 3 || $order->status == 4){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'体检码已核销，请勿重复提交'
            ));
        }else if($order->status == 2){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'体检码已取消，请勿重复提交'
            ));
        }else{
            $this->success('成功',array(
                'code'=>200,
                'data'=>[],
                'msg'=>''
            ));
        }
    }
    public function getDetail(){
        $couponCode = input('code','');
        if(empty($couponCode)){
            $this->error('参数有误');
            return false;
        }
        $order = $this->ExaminationOrderModel->where(['order_no'=>$couponCode])->find();
        $detail = $this->ExaminationOrderDetailModel->where(['order_no'=>$couponCode])->select();
        $order['items'] = $detail;
        $this->success('',array(
			'order'=>$order
		));
    }
    public function getOrderDetail(){
        $id = input('id','');
        if(empty($id)){
            $this->error('参数有误');
            return false;
        }
        $order = $this->ExaminationOrderModel->where(['id'=>$id])->find();
        $detail = $this->ExaminationOrderDetailModel->where(['order_id'=>$id])
            ->whereNotNull('report_url')->select();
        if(empty($detail) === FALSE){
            foreach ($detail as &$v){
                $v['report_time'] = date('Y-m-d H:i:d',$v['report_time']);
                $v['report_url'] = \addons\vppz\library\Vpower::dourl($v['report_url']);
            }
        }

        $this->success('',array(
			'package'=>$order,
            'itemdata'=>$detail
		));
    }
    public function hexiao(){
        $couponCode = input('examCode','');
        $hospitalid = input('hospitalId','');
        if(empty($hospitalid) || empty($couponCode)){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'参数有误'
            ));
            return false;
        }
        $order = $this->ExaminationOrderModel->where(['order_no'=>$couponCode])->find();
        if(empty($order)){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'体检码有误，请核实后使用'
            ));
        }else if(empty($order->hospital_id) === FALSE){
            if($order->hospital_id != $hospitalid){
                $this->success('成功',array(
                    'code'=>400,
                    'data'=>[],
                    'msg'=>'体检码不属于当前医院，请核实后使用'
                ));
            }
        }
        if($order->status == 3 || $order->status == 4){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'体检码已核销，请勿重复提交'
            ));
        }else if($order->status == 2){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'体检码已取消，请勿重复提交'
            ));
        }
        //更新体检订单
        $opera = [];
        $this->ExaminationOrderModel->startTrans();
        $hospital = $this->HospitalModel->find($hospitalid);
        $updatedata = array(
            'status'=>3,
            'hexiao_hospital_id'=>$hospitalid,
            'hexiao_hospital_name'=>$hospital->name,
            'exam_complete_time'=>time(),
            'updatetime'=>time()
        );
        if(empty($order->hospital_id)){
            $updatedata['hospital_id'] = $hospitalid;
            $updatedata['hospital_name']=$hospital->name;
            $updatedata['hospital_level']=$hospital->rank;
            $updatedata['hospital_address']=$hospital->address;
        }
        $opera[] = $this->ExaminationOrderModel->where(['order_no'=>$couponCode])->update($updatedata);
        $opera[] = $this->ExaminationOrderDetailModel->where(['order_no'=>$couponCode])->update(array(
            'hospital_id'=>$hospitalid,
            'hospital_name'=>$hospital->name,
            'hospital_level'=>$hospital->rank,
            'hospital_address'=>$hospital->address,
            'order_status'=>2,
            'exam_complete_time'=>date('Y-m-d H:i:s',time()),
            'updatetime' => time()
        ));
        if(\Tools::checkArrayResult($opera)){
            $this->ExaminationOrderModel->commit();
            //通知
            $AppModel = new \app\admin\model\vppz\App();
                $app = $AppModel->find(1);
                $appid = $app['wxapp_id'];
                $secret = $app['wxapp_secret'];
                if (empty($this->object)) {
                    $this->object = new \Wxchat($appid, $secret);
                }
                $accessToken = $this->object->getaccesstoken();
                if (empty($order->openid) === FALSE) {
                        $send_data = array(
                            "thing1" => array(
                                "value" => $order->exam_person_name
                            ),
                            "thing2" => array(
                                "value" => $order->package_name
                            ),
                            "thing4" => array(
                                "value" => '体检已核销完成，请排队等候体检'
                            )
                        );
                        \Wxchat::sendtmpldetail($order->openid, '0Q-gDuR7DYhFuKV_k4l8YqUQ-foAnlFOB9CnIS7peiQ', $accessToken, $send_data);
                    }
            $this->success('成功',array(
                'code'=>200,
                'data'=>$opera,
                'msg'=>''
            ));
        }else{
            $this->ExaminationOrderModel->rollback();
             $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'核销失败，请重试'
            ));
             return  false;
        }
    }
}
